#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStringList>
#include <QDebug>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , modbus_host(new ModbusHost)
    , workthread(new QThread)
{
    ui->setupUi(this);
    this->setWindowTitle("制冷控制器管理系统");
    mosbus_is_alive = false;
    ui->modbus_slave_addr->setText("1");
    qRegisterMetaType<ret_code_t>("ret_code_t"); // 注册 ret_code_t 类型

    qRegisterMetaType<QVector<QString>>("QVector<QString>");
    cfg_show_timer = new QTimer(this);
    cfg_show_timer->setInterval(500);
    env_show_timer = new QTimer(this);
    env_show_timer->setInterval(400);

    QStringList bauds = { "9600", "115200" };
    ui->baud_cbx_2->addItems(bauds);
    /**
    *       @brief 异步线程相关函数 send to thread
    */
    modbus_host->moveToThread(workthread);
    workthread->start();
    connect(ui->searchPort_btn_2,&QPushButton::clicked,this,&MainWindow::searchPort_tothread);
    connect(cfg_show_timer,&QTimer::timeout,this,&MainWindow::get_cfg_timing_tothread);
    connect(env_show_timer,&QTimer::timeout,this,&MainWindow::get_env_timing_tothread);
    connect(ui->open_serial_btn_2,&QPushButton::clicked,this,&MainWindow::connect_modbus_tothread);
     connect(ui->tabWidget, &QTabWidget::currentChanged, this, &MainWindow::onTabChanged);
    // fro thread
    connect(modbus_host,&ModbusHost::modbus_ret_code,this,&MainWindow::recv_modbus_err_code_handle);

    connect(modbus_host,&ModbusHost::modbus_task_sendSearchPort,this,&MainWindow::recv_Port_fromthread);
    connect(modbus_host,&ModbusHost::modbus_get_cfg_finish,this,&MainWindow::recv_cfg_fromthread);
    connect(modbus_host,&ModbusHost::modbus_get_env_finish,this,&MainWindow::recv_env_fromthread);
    // 请求写保持寄存器
    // emit request_write_hold_reg(reg,data)
    connect(this,&MainWindow::request_write_hold_reg,modbus_host,&ModbusHost::modbus_write_hold);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete modbus_host;
    delete workthread;
}

void MainWindow::close_all_time()
{
    cfg_show_timer->stop();
    env_show_timer->stop();
}



/**
*       @brief 异步线程相关函数
*/
// 串口 send to 线程
void MainWindow::connect_modbus_tothread()
{
    QVariantMap port_info;
    port_info["com"] = ui->serialPort_cbx_2->currentText();
    port_info["baudRate"] = ui->baud_cbx_2->currentText();
    port_info["addr"] = ui->modbus_slave_addr->text();
    QMetaObject::invokeMethod(modbus_host, "modbus_connect_slave", Qt::QueuedConnection,Q_ARG(QVariantMap,port_info));
}

void MainWindow::searchPort_tothread()
{
    QMetaObject::invokeMethod(modbus_host, "modbus_task_SearchPort", Qt::QueuedConnection);
}

void MainWindow::get_cfg_timing_tothread()
{
    QMetaObject::invokeMethod(modbus_host, "modbus_task_get_cfg", Qt::QueuedConnection);
}

void MainWindow::get_env_timing_tothread()
{
    QMetaObject::invokeMethod(modbus_host, "modbus_task_get_env", Qt::QueuedConnection);
}
// 串口 recv  from 线程
void MainWindow::recv_Port_fromthread(QStringList portList)
{
    ui->serialPort_cbx_2->clear();
    ui->serialPort_cbx_2->addItems(portList);
}

void MainWindow::recv_cfg_fromthread(QVector<QString> cfg_string)
{

    ui->regrieration_TemperationV->setText(cfg_string[0]);
    ui->password->setText(cfg_string[1]);
    ui->return_TemperationV->setText(cfg_string[2]);
    ui->compressorDelayTime->setText(cfg_string[3]);
    ui->forceRegrierationTime->setText(cfg_string[4]);
    ui->temperationCalibrationV->setText(cfg_string[5]);
    ui->temperation_MinV->setText(cfg_string[6]);
    ui->temperation_MaxV->setText(cfg_string[7]);
    ui->heatting_TemperationV->setText(cfg_string[8]);
    ui->temperation_LowWarnV->setText(cfg_string[9]);
    ui->temperation_HighWarnV->setText(cfg_string[10]);
    ui->slaveAddr->setText(cfg_string[11]);

}

void MainWindow::recv_env_fromthread(QVector<QString> env_string)
{
    ui->cur_temperatureV->setText(env_string[0]);
    ui->rely_regri_state->setText(env_string[1]);
    ui->rely_heatting_state->setText(env_string[2]);
    ui->force_regri_state->setText(env_string[3]);
    ui->low_temperature_warn->setText(env_string[5]);
    ui->high_temperature_warn->setText(env_string[6]);
    ui->beyond_minTemp_range_err->setText(env_string[7]);
    ui->beyond_maxTemp_range_err->setText(env_string[8]);
    ui->sensor_short_circuit_err->setText(env_string[9]);
    ui->water_full_err->setText(env_string[10]);
}

void MainWindow::recv_modbus_err_code_handle(ret_code_t code)
{
    qDebug()<<code<<endl;
    switch (code) {
        case     RET_CONNECT_ERR   :ui->open_serial_btn_2->setText("连接失败"); mosbus_is_alive = false;modbus_host->modbus_disconnect();close_all_time();  break;
        case    RET_CONNECT_SUCCESS:ui->open_serial_btn_2->setText("断开连接"); mosbus_is_alive = true; break;
    case    RET_DISCONNECT     :ui->open_serial_btn_2->setText("连接"); mosbus_is_alive = false; modbus_host->modbus_disconnect();close_all_time() ;    break;
        case    RET_WRITE_SUCCESS:QMessageBox::information(this, "信息", "写入成功！", QMessageBox::Ok);break;
        case    RET_WRITE_ERR:  QMessageBox::warning(this, "警告", "警告：输入范围无效！", QMessageBox::Ok);break;

    default: break;
    }
}
/**
    @brief   标签改变时
*/
void MainWindow::onTabChanged(int index)
{
    if(mosbus_is_alive!=true) return;
    switch(index)
    {
        case 0: env_show_timer->start();break;
        case 1: cfg_show_timer->start();break;
        default: break;
    }
    if(index!=0)
    {
        if(env_show_timer->isActive())
        env_show_timer->stop();
    }
    if(index!=1)
    {
        if(cfg_show_timer->isActive())
        cfg_show_timer->stop();
    }
}
//

// simlate 温度
void MainWindow::on_simulate_temp_btn_clicked()
{
    qDebug()<<"ui->simulate_temp_text->text().toInt()="<<ui->simulate_temp_text->text().toInt();
    emit request_write_hold_reg(13,ui->simulate_temp_text->text().toInt());
}


void MainWindow::on_updata_cfg_btn_clicked()
{
    for(int i=0;i<MODBUS_HOLD_REG_SIZE-2;i++)
    {
        QString lintext = QString("regri_cfg_reg_%1").arg(i);
        QLineEdit * lineEdit = findChild<QLineEdit*>(lintext);
        if(lineEdit->text().trimmed().isEmpty()) continue;
        qDebug()<< "updata "<<lintext<<" "<<lineEdit->text().toInt();
        emit request_write_hold_reg(i,lineEdit->text().toInt());

    }
}
